package com.jacklei.ch13;

import sun.security.util.Length;

/*
* */
public class PalindromeLinkedList {
    public static void main(String[] args) {
        ListNode  listNode = new ListNode(
                1,new ListNode(
                        2/*,new ListNode(
                                2,new ListNode(1,null))*/));
        PalindromeLinkedList p = new PalindromeLinkedList();
        System.out.println(p.isPalindrome(listNode));
    }
    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
    //更优雅的 找到前部分链表 进行反转 然后 用两个指针同时迭代 比对；
    public boolean isPalindrome(ListNode head) {
        if(head.next == null) return true;
        StringBuffer stringBuffer = new StringBuffer();

        ListNode low = head;
        ListNode quick = head;
        stringBuffer.append(low.val);
        int count = 1;
        while (quick.next !=null && quick.next.next != null) {
            count ++;
            quick = quick.next.next;
            low = low.next;
            stringBuffer.append(low.val);
        }
        int i = 0;
        if(quick.next == null) {
            i = 1;
        }
        low = low.next;
        stringBuffer.reverse();
        while (i < stringBuffer.length() && low != null) {
            if((stringBuffer.charAt(i) - '0')!= low.val)return false;
            i++;
            low = low.next;
        }

        return true;
    }
}
